<template>
  <div class="job-recommendation-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>智能推荐岗位</h1>
      <p class="page-subtitle">上传您的简历，AI将为您推荐最匹配的岗位</p>
    </div>

    <!-- 简历上传区域 -->
    <div class="upload-section">
      <div class="upload-card">
        <div class="upload-icon">📄</div>
        <h3>上传简历</h3>
        <p class="upload-tips">支持 PDF、Word、TXT 格式，文件大小不超过 10MB</p>
        
        <div class="upload-area" 
             :class="{ 'dragover': isDragOver, 'uploaded': uploadedFile }"
             @dragover.prevent="handleDragOver"
             @dragleave.prevent="handleDragLeave"
             @drop.prevent="handleDrop"
             @click="triggerFileInput">
          <input 
            ref="fileInput"
            type="file" 
            accept=".pdf,.doc,.docx,.txt"
            @change="handleFileSelect"
            style="display: none"
          />
          
          <div v-if="!uploadedFile" class="upload-placeholder">
            <div class="upload-icon-large">📁</div>
            <p>点击或拖拽文件到此处上传</p>
            <p class="upload-hint">支持 PDF、Word、TXT 格式</p>
          </div>
          
          <div v-else class="uploaded-file">
            <div class="file-icon">📄</div>
            <div class="file-info">
              <p class="file-name">{{ uploadedFile.name }}</p>
              <p class="file-size">{{ formatFileSize(uploadedFile.size) }}</p>
            </div>
            <button class="remove-file" @click.stop="removeFile">×</button>
          </div>
        </div>
        
        <button 
          class="upload-btn" 
          :disabled="!uploadedFile || isUploading"
          @click="uploadResume"
        >
          <span v-if="isUploading">分析中...</span>
          <span v-else>开始分析简历</span>
        </button>
      </div>
    </div>

    <!-- 简历摘要 -->
    <div v-if="resumeSummary" class="resume-summary">
      <h3>简历摘要</h3>
      <div class="summary-content">
        <pre>{{ resumeSummary }}</pre>
      </div>
    </div>

    <!-- 推荐结果 -->
    <div v-if="recommendedJobs.length > 0" class="recommendations">
      <div class="recommendations-header">
        <h3>为您推荐 {{ recommendedJobs.length }} 个岗位</h3>
        <p class="recommendations-subtitle">基于您的简历，AI为您匹配了以下岗位</p>
      </div>
      
      <div class="jobs-list">
        <div 
          v-for="(job, index) in recommendedJobs" 
          :key="job.id"
          class="job-card"
          :class="{ 'top-match': index < 3 }"
        >
          <div class="job-header">
            <div class="job-title-section">
              <h4 class="job-title">{{ job.title }}</h4>
              <p class="company-name">{{ job.company }}</p>
              <div class="job-meta">
                <span class="location">📍 {{ job.city }}</span>
                <span class="education">🎓 {{ job.education }}</span>
              </div>
            </div>
            <div class="match-score">
              <div class="score-circle" :class="getScoreClass(job.scores.fused_score)">
                {{ Math.round(job.scores.fused_score * 100) }}%
              </div>
              <span class="score-label">匹配度</span>
            </div>
          </div>
          
          <div class="job-tags">
            <span 
              v-for="tag in getJobTags(job.job_str)" 
              :key="tag"
              class="job-tag"
            >
              {{ tag }}
            </span>
          </div>
          
          <div class="job-description">
            <h5>职位描述</h5>
            <p>{{ getJobDescription(job.job_str) }}</p>
          </div>
          
          <div class="match-reason">
            <h5>推荐理由</h5>
            <p>{{ job.reason }}</p>
          </div>
          
          <div class="job-actions">
            <button class="apply-btn">立即投递</button>
            <button class="detail-btn">查看详情</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="isUploading" class="loading-overlay">
      <div class="loading-content">
        <div class="loading-spinner"></div>
        <p>正在分析您的简历，请稍候...</p>
        <p class="loading-tips">AI正在深度分析您的简历内容，这可能需要1-2分钟，请耐心等待</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import request from '../utils/request.js'

// 响应式数据
const fileInput = ref(null)
const uploadedFile = ref(null)
const isDragOver = ref(false)
const isUploading = ref(false)
const resumeSummary = ref('')
const recommendedJobs = ref([])

// 处理文件拖拽
const handleDragOver = (e) => {
  isDragOver.value = true
}

const handleDragLeave = (e) => {
  isDragOver.value = false
}

const handleDrop = (e) => {
  isDragOver.value = false
  const files = e.dataTransfer.files
  if (files.length > 0) {
    handleFile(files[0])
  }
}

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileSelect = (e) => {
  const file = e.target.files[0]
  if (file) {
    handleFile(file)
  }
}

// 处理文件
const handleFile = (file) => {
  // 检查文件类型
  const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain']
  if (!allowedTypes.includes(file.type)) {
    alert('请上传 PDF、Word 或 TXT 格式的文件')
    return
  }
  
  // 检查文件大小 (10MB)
  if (file.size > 10 * 1024 * 1024) {
    alert('文件大小不能超过 10MB')
    return
  }
  
  uploadedFile.value = file
}

// 移除文件
const removeFile = () => {
  uploadedFile.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 上传简历
const uploadResume = async () => {
  if (!uploadedFile.value) return
  
  isUploading.value = true
  
  try {
    const formData = new FormData()
    formData.append('file', uploadedFile.value)
    
    const response = await request.post(
      'rag/boss-recommend-jobs/',
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        timeout: 120000 // 增加到2分钟超时
      }
    )
    
    const { jobs, resume_summary } = response.data
    
    if (jobs && Array.isArray(jobs)) {
      recommendedJobs.value = jobs
      resumeSummary.value = resume_summary || ''
    } else {
      alert('未获取到推荐结果，请重试')
    }
  } catch (error) {
    console.error('上传失败:', error)
    if (error.code === 'ECONNABORTED') {
      alert('请求超时，简历分析需要较长时间，请重试或稍后再试')
    } else if (error.response?.status === 403) {
      alert('权限不足，请先登录后再试')
    } else {
      alert('上传失败，请检查网络连接后重试')
    }
  } finally {
    isUploading.value = false
  }
}

// 获取匹配度样式类
const getScoreClass = (score) => {
  if (score >= 0.8) return 'score-excellent'
  if (score >= 0.6) return 'score-good'
  if (score >= 0.4) return 'score-fair'
  return 'score-poor'
}

// 解析职位标签
const getJobTags = (jobStr) => {
  const tagsMatch = jobStr.match(/职位标签:([^,]+(?:,[^,]+)*)/)
  if (tagsMatch) {
    return tagsMatch[1].split(',').map(tag => tag.trim()).filter(tag => tag)
  }
  return []
}

// 获取职位描述
const getJobDescription = (jobStr) => {
  const descMatch = jobStr.match(/职位描述:([^,]+)/)
  if (descMatch) {
    return descMatch[1].trim()
  }
  return '暂无职位描述'
}
</script>

<style scoped>
.job-recommendation-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-header h1 {
  font-size: 32px;
  color: #303133;
  margin-bottom: 10px;
}

.page-subtitle {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.upload-section {
  max-width: 600px;
  margin: 0 auto 40px;
}

.upload-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.upload-card h3 {
  font-size: 20px;
  color: #303133;
  margin-bottom: 10px;
}

.upload-tips {
  color: #909399;
  font-size: 14px;
  margin-bottom: 30px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  padding: 40px 20px;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover,
.upload-area.dragover {
  border-color: #00BEBD;
  background: #f0f9ff;
}

.upload-placeholder {
  color: #606266;
}

.upload-icon-large {
  font-size: 48px;
  margin-bottom: 15px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.uploaded-file {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.file-icon {
  font-size: 32px;
}

.file-info {
  flex: 1;
  text-align: left;
}

.file-name {
  font-weight: 500;
  color: #303133;
  margin: 0 0 5px 0;
}

.file-size {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

.remove-file {
  background: #f56c6c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  cursor: pointer;
  font-size: 16px;
  line-height: 1;
}

.upload-btn {
  background: #00BEBD;
  color: white;
  border: none;
  border-radius: 6px;
  padding: 12px 30px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-btn:hover:not(:disabled) {
  background: #009a9a;
}

.upload-btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.resume-summary {
  max-width: 800px;
  margin: 0 auto 40px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.resume-summary h3 {
  color: #303133;
  margin-bottom: 15px;
}

.summary-content {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 15px;
  max-height: 200px;
  overflow-y: auto;
}

.summary-content pre {
  margin: 0;
  white-space: pre-wrap;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
}

.recommendations {
  max-width: 1000px;
  margin: 0 auto;
}

.recommendations-header {
  text-align: center;
  margin-bottom: 30px;
}

.recommendations-header h3 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.recommendations-subtitle {
  color: #606266;
  margin: 0;
}

.jobs-list {
  display: grid;
  gap: 20px;
}

.job-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
}

.job-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.job-card.top-match {
  border-left: 4px solid #00BEBD;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.job-title-section {
  flex: 1;
}

.job-title {
  font-size: 18px;
  color: #303133;
  margin: 0 0 5px 0;
  font-weight: 600;
}

.company-name {
  font-size: 14px;
  color: #606266;
  margin: 0 0 10px 0;
}

.job-meta {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.match-score {
  text-align: center;
}

.score-circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 12px;
  margin-bottom: 5px;
}

.score-excellent {
  background: #67c23a;
  color: white;
}

.score-good {
  background: #e6a23c;
  color: white;
}

.score-fair {
  background: #f56c6c;
  color: white;
}

.score-poor {
  background: #909399;
  color: white;
}

.score-label {
  font-size: 10px;
  color: #909399;
}

.job-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.job-tag {
  background: #e6f9f9;
  color: #00BEBD;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.job-description,
.match-reason {
  margin-bottom: 15px;
}

.job-description h5,
.match-reason h5 {
  color: #303133;
  font-size: 14px;
  margin: 0 0 8px 0;
}

.job-description p,
.match-reason p {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

.job-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.apply-btn,
.detail-btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.apply-btn {
  background: #00BEBD;
  color: white;
}

.apply-btn:hover {
  background: #009a9a;
}

.detail-btn {
  background: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.detail-btn:hover {
  background: #e4e7ed;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  text-align: center;
}

.loading-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #00BEBD;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .job-recommendation-container {
    padding: 15px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .upload-card {
    padding: 20px;
  }
  
  .job-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .match-score {
    align-self: flex-end;
  }
  
  .job-actions {
    flex-direction: column;
  }
}
</style>
